var app = getApp()
var fun = require('../fun.js');
var QQMapWX = require('../mapsdk.js');
var qqmapsdk ;//解析地址
Page({
  data: {
    nav:{top:app.globalData.nav_top,title:app.globalData.web,home:'show',back:'show',safe_top:app.globalData.safe_top,page:'index'},page:1,can_load:1,area:app.globalData.area,region:app.globalData.region,show_share:1,hb_index:0,refresher:true,add_fav_show:0
  },

   onLoad(op) {
      var from='direct';//从哪里来
      var id=0;
      var from_id=op.f;if(!from_id){from_id=0;from='link';}//来源id
          if (op.scene) {//扫描
            var scene = decodeURIComponent(op.scene);
            var arrPara = scene.split("&");
            var arr = [];
            for (var i in arrPara) {
              arr = arrPara[i].split("=");
              if (arr[0] == 'f') { from_id = arr[1]; }//from_id
              if (arr[0] == 'id') { id=arr[1];}//门店id
            }
           from='scan';
          }
      app.globalData.from=from;
      app.globalData.from_id=from_id;
this.data.id=id;
var key=op.key;if(key){this.setData({key:key})}
var c=op.c;if(c){this.setData({c:c})}
fun.view_add('打开首页');

   },

   onReady() {var that=this
if(app.globalData.area){
   this.setData({area:app.globalData.area})
   this.load();
   this.get_pos();
}else{//没有地区
 
this.get_pos(1);
}
if(app.globalData.region){
   this.setData({region:app.globalData.region})
}
try {
wx.checkIsAddedToMyMiniProgram({complete(res){
   if(!res.added){
   setTimeout(function(){that.setData({add_fav_show:1})},2000);
   setTimeout(function(){that.setData({add_fav_show:0})},12000);
}
}});
}catch (e) { }

   },

   get_pos(ac){//获取位置
      fun.view_add('获取位置');
      console.log('获取位置信息',app.globalData.latitude)
      var that=this;
      if(app.globalData.latitude){return;}
      
      fun.get_pos().then(res=>{console.log(res)
         if(res.err=='ok'){//用户的经纬度
           app.globalData.latitude=res.latitude; 
           app.globalData.longitude=res.longitude;
var list=this.data.list;
if(list){
for(var i in list){
var dis=0;
if(list[i].lat){
dis=fun.get_dis(list[i].lat,list[i].lng,res.latitude,res.longitude)
list[i].dis=dis;
}

}
this.setData({list:list})
}

if(ac){
//获取位置
console.log('获取城市')
qqmapsdk = new QQMapWX({key:app.globalData.map_key});
qqmapsdk.reverseGeocoder({//获取信息
   location:{latitude:res.latitude,longitude:res.longitude},
   get_poi:1,//获取附近poi点
   success(res){
     console.log('获取位置信息',res);
     var city=res.result.address_component.district;
var region=[res.result.address_component.province,res.result.address_component.city,res.result.address_component.district]
     console.log(city)
app.globalData.area=city;
that.setData({area:city,region:region})
try {
 wx.setStorageSync('area',city);
 } catch (e) {}

 try {
   wx.setStorageSync('region',region);
   } catch (e) {}
that.load()
   }
 })
}

         }else{
         if(res.errMsg=='getLocation:fail auth deny'){
this.load();

         }
         }
           })},
   
   onShow() {
   if(app.globalData.flash==1){this.load();app.globalData.flash=0}
   },

   add_fav_show(e){
      this.setData({add_fav_show:0})
   },
   load() {
   var that=this;
var c=this.data.c;if(!c){c=''}
if(this.data.can_load!=1){return}
this.data.can_load=0;
var page=this.data.page;if(!page){page=1;}
var area=this.data.area;if(!area){area=''}
var key=this.data.key;if(!key){key='';}
fun.view_add('加载首页 c:'+c+' area:'+area+' key:'+key+' page:'+page);
fun.get({ac:'get_index',c:c,page:page,area:area,key:key,id:this.data.id?this.data.id:0}).then(res=>{
fun.view_add('页面加载完成');
if(page==1){
var no_data=0;
if(!res.list){no_data=1;}
if(app.globalData.latitude && res.list){
for(var i in res.list){
var dis=0;
dis=fun.get_dis(res.list[i].lat,res.list[i].lng,app.globalData.latitude,app.globalData.longitude)
res.list[i].dis=dis;
}
}

this.setData({list:res.list?res.list:'',set:res.set,user:res.user,no_data:no_data,can_load:1,cc:res.cc,fav:res.fav,info:res.info});
if(res.user){
if(!res.user.pro && app.globalData.region){
var region=app.globalData.region;
var data={pro:region[0],city:region[1],dist:region[2]}
fun.get({ac:'user_change',data:JSON.stringify(data)}).then(res=>{})
}


}else{
console.log('登录');
app.globalData.user_id='';
app.globalData.session='';
fun.login().then(res=>{console.log(res)
   if(res.err=='ok'){
   this.setData({user:res.user});
   }
   if(res.is_new){
      this.setData({user_change_show:'show'})
   }
})

}
}else{
if(!res.list){return;}
var list=this.data.list;
for(var i in res.list){
if(app.globalData.latitude){
var dis=0;
dis=fun.get_dis(res.list[i].lat,res.list[i].lng,app.globalData.latitude,app.globalData.longitude)
res.list[i].dis=dis;
}
   list[i]=res.list[i];
}
this.setData({list:list,can_load:1});
}
})
   },


   gz(e){//关注
      fun.view_add('关注');
var set=this.data.set;
var user=this.data.user;
var info=this.data.info;
if(!user){
   wx.navigateTo({
     url: '/pages/login/index',
   });
   return;
}
wx.previewImage({
  urls: [set.qr],
})
wx.setClipboardData({
  data: '小潴微服:'+user.session,
})

app.err(info.copy);

   },
   copy_this(e){
var list=this.data.list;
var index=e.currentTarget.dataset.index;
console.log(list[index])
wx.setClipboardData({
   data: list[index].temp
 })

   },


   preview(e){
var val=e.currentTarget.dataset.val;
wx.previewImage({
  urls: [val],
})
   },

   change_area(e){
   var val=e.detail.value;
   console.log(val)
var city=val[2];
   app.globalData.area=city;
   this.setData({area:city,region:val,page:1,key:'',can_load:1});
   
   try {
    wx.setStorageSync('area',city);
    } catch (e) { }

    try {
      wx.setStorageSync('region',val);
      } catch (e) { }  
this.data.page=1;
this.can_load=1;
this.load();
   },

load_more(){
if(this.data.can_load!=1){return}
this.data.page++;
this.load();
},
select_c(e){
var val=e.currentTarget.dataset.val;
this.setData({c:val,page:1,can_load:1});
this.load()

},
img_preview(e){
var list=this.data.list;
var index=e.currentTarget.dataset.index;
var inx=e.currentTarget.dataset.inx;
console.log(index,inx,list[index].img)
var img=[];
var current='';
if(list[index].img){
for(var i in list[index].img){
img.push(list[index].img[i].img_750);
if(i==inx){current=list[index].img[i].img_750}
}
}
console.log(img)
wx.previewImage({
  urls: img,
  current:current
})

},


top_nav_hide() {
this.setData({top_nav_show:''})
   },
   main_scroll(e){
var val=e.detail.scrollTop;
if(val>=500){
if(this.data.top_nav_show!='show'){console.log('显示')
this.setData({top_nav_show:'show'})
}
}else{
   if(this.data.top_nav_show=='show'){console.log('隐藏')
   this.setData({top_nav_show:''})
   }
}

if(val>=500){
   if(this.data.top_index_show!='show'){console.log('显示')
   this.setData({top_index_show:'show'})
   }
   }else{
      if(this.data.top_index_show=='show'){console.log('隐藏')
      this.setData({top_index_show:''})
      }
   }
//console.log(val)


   },
   key_input(e) {
      var val=e.detail.value;
      this.setData({key:val})
   },
search_go(){
var key=this.data.key;if(!key){key='';}
this.data.key=key;
this.data.page=1;this.data.can_load=1;
console.log(key)
this.setData({scroll_id:'arc'})
this.load();

},
fav_add(e){fun.view_add('收藏');
var id=e.currentTarget.dataset.id;
var fav=this.data.fav;if(!fav){fav={}}
console.log(id)
fun.get({ac:'fav_add',id:id}).then(res=>{
   fav['item_'+id]=id;
   this.setData({fav:fav})
})
},
up(e){//文章置顶
   var id=e.currentTarget.dataset.id;
   fun.get({ac:'up_to_top',id:id}).then(res=>{
      app.err('置顶成功');
   })

},


   arc_go(e) {
var id=e.currentTarget.dataset.val;
wx.navigateTo({
  url: '/pages/index/detail?id='+id,
})
   },
   onShareTimeline(){fun.view_add('分享到朋友圈');
var set=this.data.set;
var img;var title=app.globalData.web;
var img=img=set.emp_bg;
var user_id=app.globalData.user_id;if(!user_id){user_id=0;}
var url='/pages/index/index?f='+user_id;
console.log('分享',img,url)
this.setData({share_box_show:''});//分享按钮窗口关闭
return {
  title:title,
  path: url,
  imageUrl: img,
}
   },
   onShareAppMessage() {fun.view_add('分享');
var set=this.data.set;
      var img;var title=app.globalData.web;
var img=img=set.emp_bg;
      var user_id=app.globalData.user_id;if(!user_id){user_id=0;}
      var url='/pages/index/index?f='+user_id;
    console.log('分享',img,url)
  this.setData({share_box_show:''});//分享按钮窗口关闭
      return {
        title:title,
        path: url,
        imageUrl: img,
      }
   },
   nietie(e){
      var key=this.data.key;if(key){return;}
      var that=this;
      wx.getClipboardData({success: (res) =>{
         console.log(res.data);
         if(res.data){
         that.setData({key:res.data});
         that.search_go();
         }
         
         }});

   },
   
   go(e){ wx.navigateTo({url: e.currentTarget.dataset.url})},
   back(e){wx.navigateBack({delta:0})},
   home(e){ wx.reLaunch({url: '/pages/index/index'})},
   rgo(e){wx.redirectTo({url: e.currentTarget.dataset.url})},
   login: function (e) {wx.navigateTo({url: '/pages/login/index',})},
   win_open(e){var c=e.currentTarget.dataset.c;this.setData({[c]:'show'})},//打开窗口
   win_close(e){var c=e.currentTarget.dataset.c;this.setData({[c]:''})},//关闭窗口
   hb_close(e){this.setData({hb_show:''})},
   get_hb(e){
    var list=this.data.list;
    var id=e.currentTarget.dataset.id;
    var arc=list['item_'+id];
    this.setData({arc:arc});
    var that=this;
    wx.showLoading({
      title: '正在创建海报，请稍后...',
    })
    
    setTimeout(function () {
      wx.hideLoading()
    }, 2000);
    
    fun.get({ac:'get_hb',id:id}).then(res=>{
    wx.hideLoading();
    var hb=res.hb;if(!hb){hb=[]}
    if(arc.img){
    for(var i in arc.img){
      hb.push({item:arc.img[i].img_750,c:'canvas',title:'详情'})
    }
    console.log(hb)
    }
    this.setData({hb:hb,hb_show:'show'});
    if(arc.img){
      setTimeout(function(res){that.draw_hb();},200)
    }
    })
       },
       hb_change(e){
    var val=e.detail.current;
    this.setData({hb_index:val})
       },
       hb_save(e){//保存图片
        fun.view_add('保存海报');
        var index=this.data.hb_index;if(!index){index=0;}
    var hb=this.data.hb;
    var file=hb[index].item;
    if(hb[index].c=='img'){
    wx.downloadFile({
      url: file,success(res){
    console.log(res)
    file=res.tempFilePath
    wx.getSetting({success(res){console.log(res)
      //if(res.authSetting['scope.writePhotosAlbum']){
          app.msg('图片保存中，请稍后');
       wx.saveImageToPhotosAlbum({filePath:file})
      //}else{app.msg('抱歉，您没有打开保存到本地相册的权限');}
          }})
      }
    })
    }else{
      wx.getSetting({success(res){console.log(res)
        //if(res.authSetting['scope.writePhotosAlbum']){
            app.msg('图片保存中，请稍后');
         wx.saveImageToPhotosAlbum({filePath:file})
        //}else{app.msg('抱歉，您没有打开保存到本地相册的权限');}
            }})
    }
            },
            draw_hb(){//绘制海报
               console.log('开始绘制海报');
            var list=this.data.hb;
            var arc=this.data.arc;
            var that=this;
            fun.get({ac:'get_qr_data',id:arc.id,server:app.globalData.server}).then(res=>{//获取二维码数据
            //获取二维码图片
            this.data.qr=res.qr;
            var canvas=wx.createSelectorQuery().select('#qr').fields({id: true,node: true,size: true}).exec(res=>{
               const canvas = res[0].node;
               var qr_data=canvas.createImage();
               qr_data.src =this.data.qr;
               qr_data.onload = () => {this.data.qr_data=qr_data;//获取二维码数据
                  this.setData({hb_show:'show'});
                  wx.hideLoading()
                  for(var i in list){
    if(list[i].c=='canvas'){
                     var query = wx.createSelectorQuery();
                     query.select('#hb_'+i).fields({
                        id: true,
                        node: true,
                        size: true
                      }).exec(this.draw.bind(this));
                    }
                  }
               }
            
            });
            })
          
            },
            draw(res){var that=this;
               var list=this.data.hb;
               var user=this.data.user;
               var arc=this.data.arc;
               var index=res[0].id.replace('hb_','');
               console.log('海报',res,res[0].id,index)
               const canvas = res[0].node
               const ctx = canvas.getContext('2d')
               const dpr = wx.getSystemInfoSync().pixelRatio;
               var width=750;
               var height=1000;
               if(!this.data.qr_data){//海报数据
               var qr_data=canvas.createImage();
               qr_data.src =this.data.qr;
               qr_data.onload = () => {this.data.qr_data=qr_data;}
            }
            //获取图片信息
            var img = canvas.createImage();
            img.src =list[index].item;
            console.log(img.src)
            img.onload = () => {
            console.log('图片尺寸',img.src,img.width,img.height)
            
            //画板尺寸
            canvas.width = width;
            var img_height=canvas.width*img.height/img.width;//图片的高度
            height=img_height+400;
            canvas.height = height;
            var hb_size=this.data.hb_size;
            if(!hb_size){hb_size={}}
            hb_size[index]={width:Math.ceil(width/1.25),height:Math.ceil(height/1.25)}
            
            this.setData({hb_size:hb_size})
            console.log('高度',img_height,canvas.width,hb_size)
            //背景
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width,  canvas.height);
            ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,img_height);
            
            ctx.moveTo(0,0);
            //标题
            ctx.font = 'normal bold 30px sans-serif';
            ctx.fillStyle = "rgba(0, 0, 0)";
            //文本尺寸
            img_height+=10;
            var line=0;var line_height=50;var metrics=0;
            var lines=[[canvas.width-460,canvas.width-400],[canvas.width-420,canvas.width-370],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50]];
            var title=Array.from(arc.temp)
            //console.log(title)
            var title_data='';
            var text_height=0;
            var text_width=ctx.measureText(arc.temp);
            if(text_width.width<(canvas.width-400)){//直接写入
               console.log('直接写')
               ctx.fillText(arc.temp,30,img_height+line_height);
            }else{
            for(var i in title){
            var line_data=lines[line];
            title_data+=title[i];
            metrics =ctx.measureText(title_data);
            console.log(title_data,line_data,line,metrics)
            if(metrics.width>=line_data[0] && metrics.width<=line_data[1]){//输出
             // console.log('蔬菜')
             text_height=img_height+line_height*(line+1);
             console.log('文本高度',text_height)
               ctx.fillText(title_data,30,text_height);
               title_data='';line++;
               if(line>=5){break;}
            }
            }
            }
            //画圆
            ctx.save();
            ctx.beginPath();
            var x=canvas.width-350;var y=img_height-150;var w=300;var r=150;var h=300;
            ctx.moveTo(x,y);
            ctx.arcTo(x+w,y,x+w,y+h,r);
            ctx.arcTo(x+w,y+h,x,y+h,r);
            ctx.arcTo(x,y+h,x,y,r);
            ctx.arcTo(x,y,x+w,y,r);
            ctx.clip();
            ctx.fillStyle = 'white';
            ctx.fillRect(x, y,w,h);
            ctx.closePath();
            
            //画二维码
            if(this.data.qr_data){
               ctx.drawImage(this.data.qr_data,x+25,y+25,250,250);
            }else{
            var qr_data=canvas.createImage();
            qr_data.src =this.data.qr;
            qr_data.onload = () => {this.data.qr_data=qr_data;
               ctx.drawImage(qr_data,x+25,y+25,250,250);
            }
            }
            
            ctx.restore();
          
            //保存到本地
            setTimeout(function(){
            wx.canvasToTempFilePath({x:0,y:0,canvas:canvas,fileType:'png',success(res){
            that.data['cavans_'+index]=res.tempFilePath;
            console.log('保存本地路径',res,index);
            list[index]['item']=res.tempFilePath;
            that.setData({hb:list})
            }})
          
            },200)
            
            }
            
            
            
            }

           , get_avatar(e){
               var user=this.data.user;if(!user){user={}}
               var user_edit_arr=this.data.user_edit_arr;
               if(!user_edit_arr){user_edit_arr={}}
               var url=e.detail.avatarUrl;
               console.log(e,url)
               fun.file_read(url).then(res=>{
                  var data='data:image/jpeg;base64,'+res
                  user.logo=data;
                  user_edit_arr.logo=res;
                  this.data.user_edit_arr=user_edit_arr;
               this.setData({user:user});
               this.submit_user_edit();
               });
            },
            user_nickname_change(e){
               var val=e.detail.value;
               console.log(val);
               var user_edit_arr=this.data.user_edit_arr;
               if(!user_edit_arr){user_edit_arr={}}
               user_edit_arr.nickname=val;
               user_edit_arr.is_change=1;
               this.setData({user_edit_arr:user_edit_arr})
            },submit_user_edit(e){
               var user_edit_arr=this.data.user_edit_arr;if(!user_edit_arr){user_edit_arr={}}
               if(e){
               if(!user_edit_arr['nickname']){app.err('请输入您的昵称');return;}
               }
               fun.get({ac:'user_info_change',data:JSON.stringify(user_edit_arr)}).then(res=>{
      this.setData({user_edit_arr:''});
      if(e){this.setData({user_change_show:''})}
      //
               })
            }
})